package com.cheng.admin.rabbitmq;

import cn.dev33.satoken.stp.StpUtil;
import com.cheng.admin.constant.Constants;
import com.cheng.admin.model.Order;
import com.cheng.admin.service.impl.OrderServiceImpl;
import com.cheng.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 用户未确认订单会自动确认
 *
 * @author 起凡
 */
@Component
@Slf4j
public class OrderConfirmProcess {
    @Autowired
    OrderServiceImpl orderService;
    @Autowired
    UserService userService;

    @RabbitListener(queues = MqConstants.DELAY_QUEUE_ORDER_CONFIRM)
    @Transactional
    public void process(Long id) {
        Order order = orderService.getById(id);
        if (order == null) {
            return;
        }
        //已经确认过了
        if (order.getOrderStatus() == Constants.ORDER_STATUS_FINISHED) {
            return;
        }
        //创建web上下文
        RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(new MockHttpServletRequest()));
        StpUtil.switchTo(order.getUserId());
        orderService.confirm(id);
    }
}